import os

from django.core.validators import RegexValidator
from django.shortcuts import render, redirect
from django import forms
from web import models
from web.utils.pagination import Pagination
from web.utils.ningan import DFAFilter



# 用户模块方法
class MessageModelForm(forms.ModelForm):

    class Meta:
        model = models.Message
        fields = ["messagename", "subject", "email", 'phone', "reply", "context", "user"]
        widgets = {
            "reply": forms.Select(attrs={"class": "form-control", "placeholder": "邮箱"}),

        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 循环找到所有的插件，添加了class="form-control"
        for name, field in self.fields.items():
            if name == "reply":
                continue
            field.widget.attrs = {"class": "form-control", "placeholder": field.label, "readOnly":"True"}

class MessageModelForm1(forms.ModelForm):
    phone = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误'), ],
    )
    email = forms.CharField(
        label="邮箱",
        validators=[RegexValidator(r'^[0-9a-za-z_]{0,19}@[0-9a-za-z]{1,13}\.[com,cn,net]{1,3}$', '邮箱格式错误'), ],
    )
    class Meta:
        model = models.Message
        fields = ["messagename", "subject", "email", 'phone', "context"]
        widgets = {
            "context": forms.Textarea(attrs={}),

        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 循环找到所有的插件，添加了class="form-control"
        for name, field in self.fields.items():
            # if name == "reply":
            #     continue
            field.widget.attrs = {"placeholder": field.label}

class CommentsModelForm(forms.ModelForm):
    phone = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误'), ],
    )


def mainmessage_list(request):
    """列表"""
    queryset = models.Message.objects.filter().all()

    page_object = Pagination(request, queryset)

    context = {
        "queryset": page_object.page_queryset,  # 分完页的数据
        "page_string": page_object.html()  # 页码
    }
    return render(request, "mainmessage_list.html", context)

os.environ["DJANGO_SETTINGS_MODULE"] = "gwcomments.settings"
curr_dir = os.path.dirname(os.path.abspath(__file__))
wordfilter_path = os.path.join(curr_dir, 'baidu_filter.txt')

def contact(request):
    print("asfdasdfasdf 范文")
    """ 提交留言（ModelForm版本）"""
    if request.method == "GET":
        form = MessageModelForm1()
        return render(request, 'contact.html', {"form": form})

    # 用户POST提交数据，数据校验。
    form = MessageModelForm1(data=request.POST, files=request.FILES)
    info_dict = request.session["info"]

    if form.is_valid():
        gfw = DFAFilter()
        path = wordfilter_path
        gfw.parse(path)
        text = form.cleaned_data["context"]
        result = gfw.filter(text)
        models.Message.objects.create(messagename=form.cleaned_data["messagename"], subject=form.cleaned_data["subject"],
                                   email=form.cleaned_data["email"], phone=form.cleaned_data["phone"],
                                   context=result, user_id=info_dict["id"])

        return redirect('/index/')

    # 校验失败（在页面上显示错误信息）
    return render(request, 'contact.html', {"form": form})


def mainmessage_listdelete(request, nid):
    """ 删除用户（ModelForm版本）"""
    models.Message.objects.filter(id=nid).delete()
    return redirect('/mainmessage/list/')
